package com.zhdl.network.servertcp;

import cn.hutool.core.util.HexUtil;
import com.project.common.bean.FrameDto;
import com.project.network.server.SerialSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class DuplexProtocolSendService {

    public static Map<String,SerialSocketServer> serialSocketServer = new ConcurrentHashMap<>();

    /**
     * 初始化 Socket
     */
    public static void init(SerialSocketServer server){
        serialSocketServer.put(server.getServerIp()+":"+server.getServerPort(),server);
//        serialSocketServer.put("001",server);
    }

    static Map<String,String> serverToClient = new ConcurrentHashMap<>();

    static List<String> clientLists = new ArrayList<>();

    public static void addClientIp(String clientIp,String serverIp){
        if(!clientLists.contains(clientIp)){
            clientLists.add(clientIp);
            log.debug("lists-->客户端Ip:{},添加成功",clientIp);
            matchingClientAndServer(clientIp,serverIp);
        }
    }

    public static void deleteClientIp(String ip){
        if (!ip.isEmpty()){
            clientLists.removeIf(clientList -> clientList.equals(ip));
            serverToClient.remove(ip);
        }
    }

    public static void matchingClientAndServer(String clientIp,String serverIp){
        String[] split = clientIp.split(":");
        String heardIp = split[0];
        serverToClient.put(heardIp,serverIp);
    }

    /**
     * 发送指令
     */
    public static void sendCmd(String clientIp,String hexData){
        byte[] bytes = HexUtil.decodeHex(hexData);
        String serverIp = serverToClient.get(clientIp);
        SerialSocketServer serialSocketServerTcp = serialSocketServer.get(serverIp);
        FrameDto packet = (FrameDto) serialSocketServerTcp.getPacket();
        packet.setFullBuff(bytes);

        int endIp = -1;
        for (String clientList : clientLists) {
            if(clientList.contains(clientIp)){
                String[] split = clientList.split(":");
                endIp = Integer.parseInt(split[1]);
            }
        }

        if(endIp != -1){
            Tio.send(serialSocketServerTcp.tioServerConfig,clientIp, endIp, (Packet) packet);
        }
//        serialSocketServerTcp.write(bytes);
        log.info("待发送数据为:{},字节数组为:{}", hexData, Arrays.toString(bytes));
    }

    public static void sendCmdToAll(String clientIp,String hexData){
        byte[] bytes = HexUtil.decodeHex(hexData);
        for (String serverIp : serialSocketServer.keySet()) {
            SerialSocketServer serialSocketServerTcp = serialSocketServer.get(serverIp);
            serialSocketServerTcp.write(bytes);
        }
    }
}
